/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fmsactionserver.server.check;

import fmsactionserver.server.actions.PlayWav;
import fmsactionserver.server.elements.Input;
import fmsactionserver.server.settings.actions.data.ActionSetting;
import fmsactionserver.server.settings.actions.data.ActionSettingsCollector;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rbs
 */
public class ActionChecker {

    ActionSettingsCollector settings;
    public ActionChecker(ActionSettingsCollector settings) {
        this.settings = settings;
    }
    
    public ActionState startActionWhenAvailable(Input input)
    {
        ActionState actionStatus = ActionState.NO_ACTION;
        
        for (ActionSetting set : settings.getSettings()){
            if (set.type == input.type)
            {
                //System.out.println("regex = " + set.ricOrFms.replaceAll("\\?", "."));

                if (input.fms1.matches(set.ricOrFms.replaceAll("\\?", ".")))
                {
                    //System.out.println("matches!");
                    //Ric ist mit Action verknüpft
                    if (!set.action.isEmpty())
                    {
                        actionStatus = ActionState.SUCESSFULL;
                        try {
                            String action = set.action.replace("%1", input.fms1);
                            action = action.replace("%2", input.fms2);
                            action = action.replace("%3", input.fms3);
                            File file = new File(action.split("")[0]);
                            System.out.println("Executing " + action + " in " + file.getAbsolutePath());
                            Runtime.getRuntime().exec(action, null, file.getParentFile());
                        } catch (IOException ex) {
                            actionStatus = ActionState.ERROR;
                            Logger.getLogger(ActionChecker.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    //Playing wav:
                    if (!set.sound.isEmpty())
                        new PlayWav(set.sound).start();
                }
            }
        }
        
        return actionStatus;
    }
}
